import React, { useState } from 'react';
import PropTypes from 'prop-types';
import Helper from '../../../components/Helper';
import Tabs, { TabPane } from '@kuiper-components/tabs';
import s from './Security.module.css';
import Titlebar from './Titlebar';
import fetch from 'API/fetch';

export default function Security({
	className,
	data,
	taskIdMap,
	jobMap,
	planData,
}) {
	const [jobsInfo, setJobsInfo] = React.useState({});
	const [loading, setLoading] = useState(false);
	const [TP, setTP] = React.useState([
		{ key: 'all', tab: 'Web资产' },
		{ key: 'vul', tab: 'Web漏洞' },
		{ key: 'ssl', tab: 'SSL安全' },
		{ key: 'securityEvent', tab: '安全事件' },
		{ key: 'content', tab: '内容违规' },
		{ key: 'changeCheck', tab: '篡改' },
		{ key: 'host', tab: '主机资产' },
	]);
	async function getData(taskType) {
		setLoading(true);
		const arr = [
			'all',
			'vul',
			'ssl',
			'securityEvent',
			'content',
			'changeCheck',
			'hostVul',
		];
		const jobsInfo_ = {};
		for (let index = 0; index < arr.length; index++) {
			const e = arr[index];
			const res = await fetch(`/api/v2/index/get_top_jobs?task_type=${e}`, {
				method: 'GET',
			}).catch(e => {
				return {};
			});
			if (res.code === 200) {
				jobsInfo_[e] = res.results;
			}
		}
		setLoading(false);
		setJobsInfo(jobsInfo_);
	}
	React.useMemo(() => {
		getData();
	}, []);
	React.useEffect(() => {
		if (planData.host_job_count > 0) {
			setTP([
				{ key: 'all', tab: 'Web资产' },
				{ key: 'vul', tab: 'Web漏洞' },
				{ key: 'ssl', tab: 'SSL安全' },
				{ key: 'securityEvent', tab: '安全事件' },
				{ key: 'content', tab: '内容违规' },
				{ key: 'changeCheck', tab: '篡改' },
				{ key: 'hostVul', tab: '主机资产' },
			]);
		}
	}, [planData]);
	const [activeKey, setActiveKey] = useState('all');
	const handleTabChange = category => {
		setActiveKey(category);
	};
	return (
		<div className={s.aviliable}>
			<div className={s.label}>
				<span className={s.text}>风险资产TOP5</span>
				<Helper
					placement="top"
					overlay="接入资产最新脆弱性监测、安全事件监测、内容违规监测、篡改监测的安全风险TOP榜"
				/>
			</div>
			{TP.length > 0 && (
				<Tabs
					className={s.tabs}
					type="card"
					activeKey={activeKey}
					tabBarPosition="top"
					onChange={handleTabChange}
				>
					{TP.map(e => {
						return (
							<TabPane key={e.key} tab={e.tab}>
								<Titlebar
									active={e.key}
									jobsInfo={jobsInfo[e.key]}
									loading={loading}
								/>
							</TabPane>
						);
					})}
				</Tabs>
			)}
		</div>
	);
}

Security.propTypes = {
	planData: PropTypes.any,
	className: PropTypes.string,
	data: PropTypes.arrayOf({
		http: PropTypes.array,
		ping: PropTypes.array,
	}),
	taskIdMap: PropTypes.object,
	jobMap: PropTypes.object,
};

Security.defaultProps = {
	className: s.aviliable,
};
